<template>
  <view id="favorites-body">
    <!-- 搜索 -->
    <view class="search"> 
      <u-search placeholder="请输入搜索内容" v-model="keyword" :showAction="false" @search="search"></u-search>
    </view>
	

    <!-- 收藏物品 -->
    <view class="orderlist">
		
      <view class="order-card" v-for="(item, index) in filteredFavoriteList" :key="index" @click="orderclick(item)">
        <!-- 物品图片 -->
		
        <view class="orderimg">
          <image :src="item.productImage" class="img"></image>
        </view>
        <view class="title">
          <text>{{ item.productTitle }}</text>
        </view>
        <view class="time">
          <text>{{ item.favoriteTime }}</text>
        </view>
        <!-- 收藏 -->
        <view class="right-sc" @click.stop="toggleFavorite(item)">
        	<image src="../static/img/collection.png" style="width: 40rpx;height: 40rpx;"></image>
        </view>
        
        <view class="price">
          <text>￥</text>
          <text style="font-size: 16px; font-weight: 600;">{{ item.productPrice }}</text>
        </view>
      </view>
	  <!-- 提示消息 -->
	    <view v-if="filteredFavoriteList.length === 0" class="no-results">
	        <text>未找到相关收藏物品</text>
	    </view>
    </view>
		

    <!-- 底部加载更多 -->
    <view class="loading">
      <u-loadmore :status="status"  :nomoreText="nomoreText" /> 
    </view>
  </view>
</template>
<script>
import { http } from "../static/service/requestAddress/rtas.js"

export default {
  data() {
    return {
      keyword: "",
      favoriteList: [], // 收藏物品列表
	  filteredFavoriteList: [] ,// 用于存储模糊查询结果
	  status:"",
	  nomoreText:"没有更多了",
    }
  },
  
  onShow() {
    this.loadData();
  },

  methods: {
    async loadData() {
      var userStr = uni.getStorageSync('user');
      var user = JSON.parse(userStr);
      const userId = user.id;
      uni.request({
        url: http + `favorites/user/${userId}`,
        method: "GET",
        complete: (res) => {
          console.log(res);
          if (res.statusCode === 200) {
            // 使用深拷贝确保数据不再是响应式的
            this.favoriteList = JSON.parse(JSON.stringify(res.data));
            // 将收藏列表按照时间最新排序
            this.favoriteList.sort((a, b) => new Date(b.favoriteTime) - new Date(a.favoriteTime));
			// 更新isFavorite状态
			this.favoriteList.forEach((item) => {
			const favoriteKey = `isFavorite_${userId}_${item.productId}`;
			const storedIsFavorite = uni.getStorageSync(favoriteKey);
			item.isFavorite = storedIsFavorite !== null ? storedIsFavorite : false;
			});
			// 如果有关键字，执行搜索操作
			if (this.keyword.trim()) {
			this.search();
			} else {
			// 如果关键字为空，显示全部数据
			this.filteredFavoriteList = this.favoriteList;
			}
          } else {
            console.error('Network request failed with status code:', res.statusCode);
          }
        }
      });
    },
	async search() {
	    // 根据输入的关键字进行模糊查询
	    if (this.keyword.trim() === "") {
	        // 如果关键字为空，显示全部数据
	        this.filteredFavoriteList = this.favoriteList;
	    } else {
	        const filteredList = this.favoriteList.filter(item =>
	            item.productTitle.includes(this.keyword) ||
	            String(item.productPrice).includes(this.keyword)
	        );
	
	        // 更新filteredFavoriteList，以便渲染模糊查询结果
	        this.filteredFavoriteList = filteredList;
	    }
	    console.log(this.filteredFavoriteList);
	},
	async orderclick(item, event) {
	  if (event && event.target && event.target.classList.contains('right-sc')) {
	    return;
	  }
	  console.log('Product ID:', item.productId);
	  try {
	    let url;
	    let pagePath;
	
	    // 根据不同的模块设置不同的接口和页面路径
	    if (item.module === 'tzmarket') {
	      url = http + `tzmarket/getProductInfo/${item.productId}`;
	      pagePath = '/tzmarket/tzmarketInfo';
	    } else if (item.module === 'nongsuke') {
	      url = http + `/nongsuke/getnongsukeone/${item.productId}`;
	      pagePath = '/nongsuke/nongsukeInfo';
	    } else {
	      // 处理其他模块的情况，或者默认情况
	      console.error('Unknown module for the selected item.');
	      return;
	    }
	
	    // 发起请求，根据 productId 获取商品信息
	    const response = await uni.request({
	      url: url,
	      method: "GET",
	    });
	    if (response[1].data) {
	      const goodsinfo = response[1].data;
	      console.log(response[1].data.date);
	
	      // 导航到对应的页面
	      uni.navigateTo({
	        url: `${pagePath}?data=${JSON.stringify(goodsinfo.date)}`
	      });
	    } else {
	      console.error('Product info not found for the selected item.');
	    }
	  } catch (error) {
	    console.error('跳转失败', error);
	  }
	},

	// 添加收藏或取消收藏
	async toggleFavorite(item) {
	    try {
	        var userStr = uni.getStorageSync('user');
	        var user = JSON.parse(userStr);
	        const userId = user.id;
			const favoriteKey = `isFavorite_${userId}_${item.productId}`;
			console.log(item.productId)
	        // 查询当前商品是否已经被用户收藏
	        const isFavoriteResponse = await uni.request({
	            url: http + "favorites/check",
	            method: "GET",
	            data: {
	                userId: userId,
	                productId: item.productId,
	            },
	        });
	
	        // 检查是否成功获取检查结果
	        if (isFavoriteResponse && isFavoriteResponse[1].data) {
	            
				console.log(item.isFavorite);
	            if (item.isFavorite) {
	                // 商品已经被用户收藏，执行取消收藏操作
	                const unfavoriteResponse = await uni.request({
	                    url: http + `favorites/remove/${userId}/${item.productId}`,
	                    method: "DELETE",
	                    data: {
	                        userId: userId,
	                        productId: item.productId,
	                    },
	                });
	
	                // 判断取消收藏的结果
	                if (unfavoriteResponse && unfavoriteResponse[1].data.code === 20050) {
	                    // 取消收藏成功
	                    console.log('取消收藏成功', unfavoriteResponse[1]);
	                    this.isFavorite = false;
	                    uni.removeStorageSync(favoriteKey);
	                    // 从收藏列表中移除对应的项
	                    const indexToRemove = this.favoriteList.findIndex(favoriteItem => favoriteItem.productId === item.productId);
	                    if (indexToRemove !== -1) {
	                        this.favoriteList.splice(indexToRemove, 1);
	                        this.loadData();
	                        // 显示取消收藏成功的提示
	                        uni.showToast({
	                            title: '已取消收藏',
	                            icon: 'success',
	                            duration: 2000
	                        });
	                    }
	                } else {
	                    console.log('取消收藏失败', unfavoriteResponse[1]);
	                    // 其他处理...
	                }
	            } else {
	            }
	        } else {
	            console.error('获取收藏状态失败，无效的响应格式', isFavoriteResponse);
	        }
	    } catch (error) {
	        console.error('操作收藏失败', error);
	        // 处理请求失败的情况
	    }
	},

	
  }
}
</script>



<style>
@import url("../static/css/componentsCss/collect/collect.css"); 




</style>
